package com.wuze.sprintboot.netty.util;

import com.wuze.sprintboot.netty.annotation.nettyController;
import com.wuze.sprintboot.netty.annotation.nettyInterceptor;
import com.wuze.sprintboot.netty.starter.NettyHttpServer;
import com.wuze.sprintboot.netty.entity.Path;
import com.wuze.sprintboot.netty.handler.HttpServerHandler;
import org.springframework.beans.BeansException;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
import org.springframework.stereotype.Component;

import java.lang.reflect.Method;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Component
public class AppUtil implements ApplicationContextAware {

    //路径和方法映射
    private static final  HashMap<String, Method> Path_Method_Map = new HashMap<>();
    //路径和beans的映射
    private static final  HashMap<String, Object> Path_Bean_Map = new HashMap<>();
    //拦截器
    public static List<Object> Interceptor_List = new ArrayList<>();

    @Value("${server.port}")
    private int port;

    private HttpServerHandler httpServerHandler = new HttpServerHandler();


    public static HashMap<String, Method> getPath_Method_Map(){
        return Path_Method_Map;
    }

    public static HashMap<String, Object> getPath_Bean_Map(){
        return Path_Bean_Map;
    }



    @Override
    public void setApplicationContext(ApplicationContext ctx) throws BeansException {
        Map<String, Object> beans = ctx.getBeansWithAnnotation(nettyController.class);

        for (Map.Entry<String, Object> entry : beans.entrySet()) {
            Object handler = entry.getValue();
            nettyController annotation = handler.getClass().getAnnotation(nettyController.class);
            Method[] methods = handler.getClass().getMethods();
            for (Method method : methods) {
                nettyController ann = method.getAnnotation(nettyController.class);
                if( ann != null){
                    Path path = new Path(annotation.value()+ann.value(), ann.method());
                    Path_Method_Map.put(path.toString(),method);
                    Path_Bean_Map.put(path.toString() , handler);
                }
            }
        }

        beans = ctx.getBeansWithAnnotation(nettyInterceptor.class);
        for (Map.Entry<String, Object> entry : beans.entrySet()) {
            Interceptor_List.add(entry.getValue());
        }

        //启动netty
        new NettyHttpServer().start(port,httpServerHandler);

    }

}
